package cn.wx;

import cn.wx.common.WxServiceRegister;
import cn.wx.common.WxServiceRegisterPostProcessor;
import cn.wx.properties.Agent;
import cn.wx.properties.WxCpProperties;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.config.WxCpConfigStorage;
import org.springframework.core.annotation.Order;
import org.springframework.util.CollectionUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static cn.wx.properties.WxCpProperties.PREFIX;

/**
 * 微信公众平台注册,使用配置文件的方式
 *
 * @author: sunshaoping
 * @date: Create by in 5:11 下午 2020/5/25
 */
@Order(11)
@AllArgsConstructor
public class WxCpServiceRegisterPostProcessor implements WxServiceRegisterPostProcessor {

    private final WxCpProperties properties;

    private final WxCpConfigStorageFactory<Agent> wxCpConfigStorageFactory;

    @Override
    public void processor(WxServiceRegister wxServiceRegister) {

        properties.verification(PREFIX);
        WxCpService defWxCpService = createWxCpService(properties);
        wxServiceRegister.register(properties.getName(), defWxCpService);

        List<Agent> agents = properties.getAgents();
        if (CollectionUtils.isEmpty(agents)) {
            return;
        }

        Set<String> set = new HashSet<>(agents.size() + 1);
        set.add(properties.getName());
        for (int i = 0; i < agents.size(); i++) {
            Agent agent = agents.get(i);
            String prefix = PREFIX + ".agents[" + i + "]";
            agent.verification(prefix);
            String name = agent.getName();
            final WxCpService service = createWxCpService(agent);
            if (set.contains(name)) {
                throw new IllegalStateException(PREFIX + ".agents[" + i + "].name=" + name + ",已存在");
            }
            set.add(name);
            //注册bean
            wxServiceRegister.register(name, service);
        }
    }

    private WxCpService createWxCpService(Agent agent) {
        WxCpService service = new WxCpServiceImpl();
        WxCpConfigStorage configStorage = wxCpConfigStorageFactory.create(this.properties.getCorpId(), agent);
        service.setWxCpConfigStorage(configStorage);
        return service;
    }

}
